var popupObj = {};

popupObj.loadDataAndRenderTable = function() {
    // Usage
    layui.use(function(){
        var layer = layui.layer;

        // 读取自定义键名的数据
        chrome.storage.local.get(['kq_data', 'kq_handle_obj', 'query_kq_time'], function(result) {
            console.log('Stored result:', result);
            console.log('Stored kq_data:', result.kq_data);
            console.log('Stored kq_handle_obj:', result.kq_handle_obj);            
            console.log('Stored query_kq_time:', result.query_kq_time);
            let kq_data = result.kq_data;
            let kq_handle_obj = result.kq_handle_obj;
            let query_kq_time = result.query_kq_time

            // 使用 jQuery 修改 HTML 内容
            $('#currentDate').text(query_kq_time);
            for (let i = 0; i < kq_data.length; i++) {
                let item = kq_data[i];
                const date = item['date'];
                if (kq_handle_obj == undefined) {
                    break;
                }

                if (date in kq_handle_obj) {
                    // 如果 kq_handle_obj 中有该日期，将其对应的值赋给 handled_flag
                    item['handled_flag'] = kq_handle_obj[date];
                }
            }
            
            popupObj.kq_data = kq_data;
            popupObj.kq_handle_obj = kq_handle_obj;
            popupObj.query_kq_time = query_kq_time;

            if (kq_data.length == 0) {
                return ;
            }

            var table = layui.table;
            var form = layui.form;
            var util = layui.util;
            table.render({
                elem: '#ID-table-demo-templet',
               // url:'https://unpkg.com/outeres@0.1.3/json/2/table/user.json', // 此处为静态模拟数据，实际使用时需
               data: kq_data,
                page: true,
                height: '315px',
                cols: [[
                    {type: 'checkbox', fixed: 'center'},
                    // 未自定义模板的普通列
                    {field:'date', fixed: 'center', width:120, title: 'date', sort: true},
                    // 模板 - 选择器写法
                    {field:'types', width:160, fixed: 'center', title: 'types', templet: '#ID-table-demo-templet-user'},
                    // {field: 'handled_flag', title: '是否处理', width: 130, unresize: true, align: 'center', templet: '#TPL-dropdpwn-demo'},
                    {field: 'handled_flag', title: '是否处理', minWidth: 150, templet: '#TPL-select-demo'},
                ]],
                done: function(res, curr, count){
                    var options = this;
                    
                    // 获取当前行数据 - 自定义方法
                    table.getRowData = function(tableId, elem){
                      var index = $(elem).closest('tr').data('index');
                      return table.cache[tableId][index] || {};
                    };
                    // 展示数据 - 仅用于演示
                    var showData = function(data) {
                      return layer.msg('当前行最新数据：<br>'+ util.escape(JSON.stringify(data)), {
                        offset: '16px',
                        anim: 'slideDown'
                      });
                    };
                    
                    // layui form select 事件
                    form.on('select(select-demo)', function(obj){
                        var value = obj.value; // 获取选中项 value
                        // 获取当前行数据(如 id 等字段，以作为数据修改的索引)
                        var data = table.getRowData(options.id, obj.elem);
                        // 更新数据中对应的字段
                        data.handled_flag = value;

                        // 显示当前行最新数据 - 仅用于示例展示
                        // showData(data);
                        
                        if (popupObj.kq_handle_obj == undefined) {
                            popupObj.kq_handle_obj = {};                        
                        }
                        popupObj.kq_handle_obj[data['date']] = value;
                        chrome.storage.local.set({ kq_handle_obj: popupObj.kq_handle_obj }, function() {
                            console.log('kq_handle_obj has been saved locally.');
                        });
                    });
                }
            });
        });

        var form = layui.form;
    });
}

$(function () {
    popupObj.loadDataAndRenderTable();

    // 每隔 n 秒钟自动执行一次
    var n = 60; // 设定间隔的秒数
    setInterval(popupObj.loadDataAndRenderTable, n * 1000); // 每隔 n 秒执行
});